package jzqb.dao.impl;

import cnki.tpi.base.DataContext;
import cnki.tpi.base.DataSourceManager;
import cnki.tpi.kbatis.sqlsession.SqlSession;
import cnki.tpi.kbatis.utils.DataSourceUtil;
import com.kbase.jdbc.ConnectionImpl;
import haha.life.normal.FileUtil;
import jzqb.bo.AdminDepartmentBo;
import jzqb.dao.AdminDepartmentDao;
import jzqb.po.AdminDepartmentPo;
import jzqb.po.AdminUserPo;
import kbase.KBaseClient;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import java.io.*;
import java.util.ArrayList;
import java.util.List;


@Repository
public class AdminDepartmentDaoImpl implements AdminDepartmentDao {

    @Autowired
    private DataSourceManager kbaseDs;

    @Autowired
    private DataContext dataContext;

    @Value("${filePath.recPath}")
    private String recPath;

    @Override
    public List<AdminDepartmentPo> cutList(AdminDepartmentBo adminDepartmentBo) {
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminDepartmentDao.getDepartmentList";
        List<AdminDepartmentPo> cutList = sqlSession.selectList(statementId, adminDepartmentBo,false);
        /*-start-查询部门的上级部门的名字(一个部门只可能一个上级部门)*/
        ArrayList<String> pids = new ArrayList<String>();
        for (AdminDepartmentPo po:cutList){
            pids.add("部门编号=" + po.getPDepartmentCode());
        }
        String condition = String.join(" or ",pids);
        String statementId_parentName = "jzqb.dao.AdminDepartmentDao.getParentName";
        List<AdminDepartmentPo> cutList_parentName = sqlSession.selectList(statementId_parentName, condition,false);
        for (AdminDepartmentPo resPo:cutList){
            for (AdminDepartmentPo parentPo:cutList_parentName){
                if (resPo.getPDepartmentCode().equals(parentPo.getDepartmentCode())){
                    resPo.setPDepartmentName(parentPo.getDepartmentName());
                    break;
                }
            }
        }
        /*- end -查询部门的上级部门的名字(一个部门只可能一个上级部门)*/

        /*-start-查询部门的领导的名字(一个部门可能多个领导)*/
        ArrayList<String> leaderids = new ArrayList<String>();
        for (AdminDepartmentPo po:cutList){
            String lederidsOfOneDept = po.getLeaderIDs();
            for (String leaderid:lederidsOfOneDept.split(";")){
                if (!leaderid.equals("")){
                    leaderids.add("ID=" +leaderid);
                }
            }
        }
        String condition_ = String.join(" or ",leaderids);
        String statementId_leaderName = "jzqb.dao.AdminUserInfoDao.getLeaderName";
        List<AdminUserPo> cutList_LeaderName = sqlSession.selectList(statementId_leaderName, condition_,false);
        for (AdminDepartmentPo resPo:cutList){
            ArrayList<String> leaderNames = new ArrayList<String>();
            for (String leaderid : resPo.getLeaderIDs().split(";")){
                for (AdminUserPo leaderPo:cutList_LeaderName){
                    if (leaderid.equals(leaderPo.getId())){
                        leaderNames.add(leaderPo.getName());
                    }
                }
            }
            resPo.setLeaderNames(String.join(";",leaderNames));
        }
        /*- end -查询部门的领导的名字(一个部门可能多个领导)*/


        return cutList;
    }

    @Override
    public long cutCount(AdminDepartmentBo adminDepartmentBo) {
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminDepartmentDao.getDepartmentListCount";
        long num=sqlSession.getCount(statementId,adminDepartmentBo);
        return num;
    }

    @Override
    public List<AdminDepartmentPo> findAllDept() {
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminDepartmentDao.findAllDept";
        return sqlSession.selectList(statementId,null,false);
    }

    @Override
    public List<AdminDepartmentBo> getDeptNameById(String deptId) {
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminDepartmentDao.getDeptNameById";
        return sqlSession.selectList(statementId,deptId,false);
    }

    @Override
    public boolean editLeader(AdminDepartmentPo adminDepartmentPo){
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String editLeader = "jzqb.dao.AdminDepartmentDao.editLeader";
        boolean res_1 =sqlSession.executeInsert(editLeader,adminDepartmentPo);
        return res_1;
    }

    @Override
    public boolean isDepartmentcodeExist(String id){
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminDepartmentDao.isDepartmentcodeExist";
        AdminDepartmentPo obj = sqlSession.selectOne(statementId,id,false);
        if (obj==null){
            return false;
        }else{
            return true;
        }
    }

    @Override
    public boolean addDepartment(AdminDepartmentPo departmentPo, String type){
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        if (type.equals("add")){
            String statementId = "jzqb.dao.AdminDepartmentDao.addDepartment";
            boolean res = sqlSession.executeInsert(statementId,departmentPo);
            return res;
        }else if (type.equals("edit")){
            String statementId = "jzqb.dao.AdminDepartmentDao.editDepartment";
            boolean res = sqlSession.executeInsert(statementId,departmentPo);
            return res;
        }else {
            return false;
        }
    }

    @Override
    public boolean deleteDepartment(AdminDepartmentPo departmentPo){
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminDepartmentDao.deleteDepartment";
        boolean res = sqlSession.executeInsert(statementId,departmentPo);
        return res;
    }

    /**
     * 复制文件,并删除原文件
     * @param s 文件的临时位置
     * @param t 文件的数据库目标位置
     * @return 执行结果
     */
    public Boolean moveTempFileToDBFile(String s, String t,String...arg) {
        ConnectionImpl conn = null;
        try {
            conn = (ConnectionImpl) this.kbaseDs.getConnection();
            int hCon = conn.getConnectionHset();
            KBaseClient kBaseClient = conn.getKbaseClient();
            //int nRet = kBaseClient.KBase_WriteFile(hCon, s, t);
            String tPath = t.substring(0, t.lastIndexOf("\\"));
            String sPath = s.substring(0, s.lastIndexOf("\\"));
            int tempRet = kBaseClient.KBase_MakeDir(hCon, tPath);
            int nRet = kBaseClient.KBase_WriteFile(hCon, s, t);
            if (nRet < 0) {
                return false;
            }
            else if (nRet == 0){
                //写入文件到DB正常,删除临时文件
                if (arg.length==0){
                    FileUtil.deleteFile(s);
                }else{
                    if (arg[0].equals("notDeleteDir")){}
                }
                return true;
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        finally {
            try {
                if (conn != null && !conn.isClosed())
                    conn.close();
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    }


    @Override
    public boolean writeExcelData(JSONArray jsonArray) throws IOException {
        // 1 生成REC内容
        String recStr ="";
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject lineObject = jsonArray.getJSONObject(i);
            String orgid = lineObject.get("orgid").toString();
            String orgName = lineObject.get("orgName").toString();
            String parentId = lineObject.get("parentId").toString();


            recStr += "<REC>\n";
            recStr += String.format("<部门编号>=%s\n",orgid);
            recStr += String.format("<部门名称>=%s\n",orgName);
            recStr += String.format("<上级部门编号>=%s\n",parentId);
        }

        // 2 先把rec文件保存在 springboot服务器(文件夹不必提前新建)
        File recFile = new File(recPath + "\\" + "REC_department.txt");
        if(!recFile.getParentFile().exists()){
            recFile.getParentFile().mkdirs();
        }
        recFile.createNewFile();
        String  recFilePath = recFile.toString();
        OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(recFilePath), "GB2312");
        BufferedWriter writer = new BufferedWriter(write);
        writer.write(recStr);
        writer.close();

        // 3 再把rec文件从springboot服务器 复制到 kbase服务器,复制后,删除springboot端文件(kbase端,文件夹不必提前新建)
        boolean res1 = moveTempFileToDBFile(recFilePath,recFilePath);

        // 4 生成优化键脚本内容
        String tableName = "YQTBMB";
        String Key = "部门编号";
        String script_content = String.format(
                "CREATE OPTIMIZEKEY %s ON TABLE %s\n" +
                        "\n" +
                        "EXCLUSIVE INSERT INTO TABLE %s WITH KEY=%s\n" +
                        "\tINFILE \"%s\"\n" +
                        "\n" +
                        "DROP OPTIMIZEKEY %s ON TABLE %s"
                ,Key,tableName
                ,tableName,Key
                ,recFilePath
                ,Key,tableName
        );

        // 5 先把脚本文件保存在 springboot服务器(文件夹不必提前新建)
        File scriptFile = new File(recPath + "\\" + "REC_department_script.txt");
        if(!scriptFile.getParentFile().exists()){
            scriptFile.getParentFile().mkdirs();
        }
        scriptFile.createNewFile();
        String  scriptFilePath = scriptFile.toString();
        OutputStreamWriter write_script = new OutputStreamWriter(new FileOutputStream(scriptFilePath), "GB2312");
        BufferedWriter writer_script = new BufferedWriter(write_script);
        writer_script.write(script_content);
        writer_script.close();

        // 6 再把脚本文件从springboot服务器 复制到 kbase服务器,复制后,删除springboot端文件(kbase端,文件夹不必提前新建)
        boolean res2 = moveTempFileToDBFile(scriptFilePath,scriptFilePath);

        // 7 运行脚本
        String sql = String.format("DBUM UPDATE TABLE BY \"%s\"",scriptFilePath);
        int excuteRECscript = dataContext.excuteSql(sql);
        if (excuteRECscript==0){
            return false;
        }else{
            return true;
        }
    }


    @Override
    public boolean isDptEmpty(AdminDepartmentPo departmentPo) {
        /*
        * departmentPo-->部门id-->是否有人属于这个部门(用户表)-->有人-->false
        *                                                  |-->无人-->true
        * */
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminDepartmentDao.getAllUserOfOneDept";
        List<AdminDepartmentBo> res = sqlSession.selectList(statementId,departmentPo,false);
        if (res.size()==0){
            return true;
        }else{
            return false;
        }
    }
}
